// 开发时使用的gulp配置文件
const gulp = require('gulp'); // 引入gulp
const uglify = require('gulp-uglify'); // 引入压缩js插件
const cleanCss = require('gulp-clean-css'); // 引入压缩css插件
const concat = require('gulp-concat'); // 引入合并文件插件
const rename = require('gulp-rename'); // 引入重命名插件
const browserSync = require('browser-sync').create(); // 引入browser-sync插件 用于热更新
const nodemon = require('gulp-nodemon');  // 引入gulp-nodemon插件 用于开启服务器
const { gulpJsPath, gulpCssPath, gulpPugPath, gulpDistPath,gulpServeDir,gulpIgnoreList} = require('./src/config'); // 引入配置文件
const path = require('path');

gulp.task('node', gulp.series((d)=>{
  nodemon({
      script: './bin/www', //入口文件
      watch: gulpServeDir,
      env: { 'NODE_ENV': 'development' },
      ignore: gulpIgnoreList,
  }).on('start', function () {
      d();
  })
}));

// 启动服务
gulp.task('serve', gulp.parallel('node',gulp.series(() => {
  browserSync.init({
      proxy: 'http://localhost:4567',
      ws: true,
      port: 4568,
      files: [gulpDistPath+'/**/*',gulpPugPath+'/**/*'],
  })
})));

gulp.task("devBuild", gulp.series((cb) => {
  gulp.src([gulpJsPath+'/tools/*',gulpJsPath+'/utils/*',gulpJsPath+'/crud.js',gulpJsPath+'/index.js'])
      .pipe(concat('all.js'))
      .pipe(gulp.dest(gulpDistPath+'/js'));
  gulp.src(gulpCssPath+'/**/*')
      .pipe(concat('all.css'))
      .pipe(gulp.dest(gulpDistPath+'/css'));
  cb();
}));

gulp.task('build', gulp.series((done) => {
  gulp.src([gulpJsPath+'/tools/*',gulpJsPath+'/utils/*',gulpJsPath+'/crud.js',gulpJsPath+'/index.js'])
      .pipe(rename({suffix: '.min'}))
      .pipe(concat('all.js'))
      .pipe(uglify())
      .pipe(gulp.dest(gulpDistPath+'/js'));
  gulp.src(gulpCssPath+'/**/*')
      .pipe(rename({suffix: '.min'}))
      .pipe(concat('all.css'))
      .pipe(cleanCss())
      .pipe(gulp.dest(gulpDistPath+'/css'));
  done();
}));

gulp.task('watch', gulp.series(() => {
  gulp.watch( ['public/javascripts/**/*.*','public/stylesheets/**/*.*'],{ ignoreInitial: false },gulp.series('devBuild'));
}));

// 默认任务
gulp.task('default', gulp.parallel('serve','watch'));